This is testprint.c in view mode; [Download] [Up]
#include <stdio.h>
#define CPREC 12 /* fixed precision for conversion of doubles to strings */
#define WBUFSZ 128 /* size of buffer - should be big enough to hold
results of any conversion */
#define CVFORMAT "%.*e"
static char wbuf[WBUFSZ]; /* work buffer for number output formatting */
extern int atoi(const char *);
extern char *strrchr(const char*, int);
/*
* This function is doing what really "%g" sprintf() is supposed
* to do, but it is not doing on NeXT machines, because is plainly
* broken and NeXT does not want to be bothered to fix it.
*
* For simplicity we will use here a fixed precision
*
* Returns a number of characters written to 'wbuf' without
* counting a trailing 0.
*
* This code is based on a code for sgfmt() from gawk sources.
*/
static int
dtostring(/* int prec, */ double val)
{
int precision, count;
char *pos, *dot;
char cvfmt[] = CVFORMAT; /* first we will try this */
if (val == 0.0) {
wbuf[0] = '0';
wbuf[1] = '\0';
return 1;
}
/* precision = prec - 1; */
precision = CPREC - 1;
count = sprintf(wbuf, cvfmt, precision, val);
if ((pos = strrchr(wbuf, 'e')) != NULL) { /*exponent starts here */
int exp = atoi(pos + 1);
if (exp >= -4 && exp <= precision) {
/* try again in 'f' format */
*(cvfmt + (sizeof(cvfmt) - 2)) = 'f';
precision -= exp;
count = sprintf(wbuf, cvfmt, precision, val);
pos = wbuf + count;
/* a bit of paranoia, but play it safe */
while (*--pos == ' ')
count -= 1;
pos += 1;
}
/* remove trailing zeros */
if (NULL != (dot = strrchr(wbuf, '.'))) {
while ( pos > dot && *--pos == '0')
precision -= 1;
if (dot == pos)
precision -= 1;
if (precision < 0)
precision = 0;
count = sprintf(wbuf, cvfmt, precision, val);
}
else {
*pos = '\0';
}
}
return count;
}
double data[] = { 123456789,
123456789012.0,
5.35,
0,
4.0,
12.0,
1245.237,
123.12,
10e+27};
int
main(int argc, char **argv)
{
int count = sizeof(data) / sizeof(double);
int i, t;
int prec;
/***
if (argc > 1) {
prec = atoi(argv[1]);
}
else {
prec = CPREC;
}
***/
for (i = 0; i < count; i++) {
t = dtostring(/* prec, */ data[i]);
printf("%2d %2d %s\n", i, t, wbuf);
}
return 0;
}
These are the contents of the former NiCE NeXT User Group NeXTSTEP/OpenStep software archive, currently hosted by Netfuture.ch.